from selenium import webdriver
import time
import random
import os
import csv


class Company(object):

    options = webdriver.ChromeOptions()
    # # 无界面参数
    # options.add_argument('--headless')

    wbc = webdriver.Chrome(options=options)

    def get_info(self, company):
        self.wbc.get('http://mnews.gw.com.cn/wap/style/temp/f10/industrialStanding.html?code={}'.format(company))
        time.sleep(random.randint(2, 3))

        # 执行js脚本，获取动态加载数据
        self.wbc.execute_script(
            # 把进度条拉到最下面
            'window.scrollTo(0,document.body.scrollHeight)'
        )
        # 获取行业名称
        in_title = self.wbc.find_element_by_xpath('//div[@class="table"]/h4/strong').text
        # 获取总市值 过滤市值偏低项
        html_ts = self.wbc.find_elements_by_xpath('//section[@class="hydw-detail-item"][1]//ol/li')

        t_list = []
        # 获取前1/3,同时必须大于100亿的公司
        for i in range(1, int((len(html_ts)/3))):
            tr = html_ts[i]
            total = tr.find_element_by_xpath('./span[3]').text
            num = total[0:-1]
            if float(num) > 100.0:
                name = html_ts[i].find_element_by_xpath('./span[1]').text
                t_list.append(name)
        print(t_list)

        # 获取前1/10,同时必须大于100亿的公司,列为必须查询的头部公司
        require_list = []
        for i in range(1, int((len(html_ts) / 10))):
            tr = html_ts[i]
            total = tr.find_element_by_xpath('./span[3]').text
            num = total[0:-1]
            if float(num) > 100.0:
                name = html_ts[i].find_element_by_xpath('./span[1]').text
                require_list.append(name)
        print(require_list)

        # 点击企业估值
        self.wbc.find_element_by_xpath('//ul[contains(@class,"tab4")]/li[3]').click()
        # 获取市盈率
        index = 0
        html_t1 = self.wbc.find_elements_by_xpath('//section[@class="hydw-detail-item"][3]//ol/li')
        t1_list = []
        for t1 in html_t1[5:]:
            name = t1.find_element_by_xpath('./span[1]').text
            t_n = t1.find_element_by_xpath('./span[3]').text
            t1_list.append((name, t_n))
        print(t1_list)

        index += 1
        html_tt = self.wbc.find_elements_by_xpath('//section[@class="hydw-detail-item"][3]/ul/li')
        html_tt[index].click()
        # 市销率
        html_t2 = self.wbc.find_elements_by_xpath('//section[@class="hydw-detail-item"][3]//ol/li')
        t2_list = []
        # 取前1/4
        for t2 in html_t2[5:int(len(html_t2)/2)]:
            name = t2.find_element_by_xpath('./span[1]').text
            t_n = t2.find_element_by_xpath('./span[3]').text
            t2_list.append((name, t_n))
        # 取必查数据中数据
        for t2 in html_t2[5:]:
            name = t2.find_element_by_xpath('./span[1]').text
            t_n = t2.find_element_by_xpath('./span[3]').text
            if name in require_list:
                if not (name, t_n) in t2_list:
                    t2_list.append((name, t_n))
        print(t2_list)

        index += 1
        html_tt[index].click()
        # 市现率
        html_t3 = self.wbc.find_elements_by_xpath('//section[@class="hydw-detail-item"][3]//ol/li')
        t3_list = []
        # 取前1/4
        for t3 in html_t3[5:int(len(html_t3)/2)]:
            name = t3.find_element_by_xpath('./span[1]').text
            t_n = t3.find_element_by_xpath('./span[3]').text
            t3_list.append((name, t_n))
        # 取必查数据中数据
        for t3 in html_t3[5:]:
            name = t3.find_element_by_xpath('./span[1]').text
            t_n = t3.find_element_by_xpath('./span[3]').text
            if name in require_list:
                if not (name, t_n) in t3_list:
                    t3_list.append((name, t_n))
        print(t3_list)
        index += 1
        html_tt[index].click()
        # ev/ebitda
        html_t4 = self.wbc.find_elements_by_xpath('//section[@class="hydw-detail-item"][3]//ol/li')
        t4_list = []
        for t4 in html_t4[5:]:
            name = t4.find_element_by_xpath('./span[1]').text
            t_n = t4.find_element_by_xpath('./span[3]').text
            t4_list.append((name, t_n))
        print(t4_list)
        total_list = []
        for t in t_list:
            for t1 in t1_list:
                if t1[0] == t:
                    for t2 in t2_list:
                        if t2[0] == t:
                            for t3 in t3_list:
                                if t3[0] == t:
                                    for t4 in t4_list:
                                        if t4[0] == t:
                                            total_list.append((t, t1[1], t2[1], t3[1], t4[1]))
                                            break
                                    break
                            break
                    break
        print(total_list)
        self.save_infos(name=in_title, data=total_list)

    def save_infos(self, name, data):
        path_have = os.path.exists('./company')
        if not path_have:
            os.makedirs('./company')
        save_path = './company/{}.csv'.format(name)
        if not os.path.exists(save_path):
            with open(save_path, 'a', encoding='utf-8-sig') as f:
                cf = csv.writer(f)
                cf.writerow(("股票名称", "市盈率:股价收益比率", "市销率:投资价值", "市现率:每股现金流量的比率", "ev/ebitda:企业价值倍数"))
                cf.writerows(data)


if __name__ == '__main__':
    c_line = input("请输入股票号码：")
    if c_line.startswith('60'):
        c_line = 'SH' + c_line
    else:
        c_line = 'SZ' + c_line
    c_info = Company()
    c_info.get_info(c_line)

    # c_list = ["SH601211",
    #           "SZ300244",
    #           "SH600522",
    #           "SH600309",
    #           "SH600031",
    #           "SZ300741",
    #           "SZ300676",
    #           "SZ002463",
    #           "SZ300144",
    #           "SZ002340",
    #           "SH601298",
    #           "SZ002595",
    #           "SH601100",
    #           "SZ300498",
    #           "SH600050",
    #           "SH601636",
    #           "SZ002430",
    #           "SZ002049",
    #           "SZ300003",
    #           "SH600887",
    #           "SZ300251",
    #           "SH600352",
    #           "SH600690",
    #           "SH600193",
    #           "SZ300433",
    #           "SZ002607",
    #           "SH601360",
    #           "SH600048",
    #           "SH601318"]
    # c_info = Company()
    # for c in c_list:
    #     c_info.get_info(c)
    #     time.sleep(2)



